package com.gdk.ksoft.ui.works;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.data.entry.tables.BankTable;
import com.gdk.ksoft.data.entry.tables.CustomerDebtTable;
import com.gdk.ksoft.data.entry.tables.CustomerTable;
import com.gdk.ksoft.data.entry.tables.CustomerTypeTable;
import com.gdk.ksoft.data.entry.tables.DeliverGoodsTable;
import com.gdk.ksoft.data.entry.tables.SaleStatisticsTable;
import com.gdk.ksoft.ui.MainActivity;
import com.gdk.ksoft.assembly.utils.extensions.FormatUtils;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客户收欠款结算页面
 */
public class DebtStatisticsActivity extends Activity {

    @ViewInject(R.id.pdebtStatistics_txtTitle) private TextView txtTitle;//页面标题
    @ViewInject(R.id.pdebtStatistics_txtIcon) private TextView txtIcon;//客户头像
    @ViewInject(R.id.pdebtStatistics_txtCustomerName)private TextView txtCustomerName;//客户名称
    @ViewInject(R.id.pdebtStatistics_txtCustomerAddress)private TextView txtCustomerAddress;//客户地址
    @ViewInject(R.id.pdebtStatistics_txtContactor)private TextView txtContactor;//联系人信息
    @ViewInject(R.id.pdebtStatistics_txtContacts)private TextView txtDelieverGoodsInfo;//收货人信息
    @ViewInject(R.id.pdebtStatistics_txtDistace)private TextView txtDistance;//距离信息
    @ViewInject(R.id.pdebtStatistics_txtStatisticsMoney)private TextView txtStatisticsMoney;//总金额
    @ViewInject(R.id.pdebtStatistics_txtBank)private TextView txtBank;//银行方式
    @ViewInject(R.id.pdebtStatistics_txtPayWay)private TextView txtPayWay;//交易方式
    @ViewInject(R.id.pdebtStatistics_etMaling)private EditText etMaling;//抹零金额

    private String[] bankNames = null;//银行账户集合
    private int[] bankIds = null;//银行账户ID集合
    private int selectorIndex = 0;//索引选择器
    private int netCustomerId = 0;//客户网络ID
    private int netAddressId = 0;//客户送货地址网络ID
    private double totalMoney = 0;//总金额
    private ArrayList<CustomerDebtTable> lstCustomerDebtInfo = null;//订单数据的详细情况
    private DbUtils dbUtils;//数据库操作对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debt_statistics);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(DebtStatisticsActivity.this).getDbUtils();
        Intent intent = getIntent();
        if(intent!=null){//获取上个页面传过来的数据
            netCustomerId = intent.getIntExtra("netCustomerId", 0);//获取客户网络ID
            netAddressId = intent.getIntExtra("netAddressId", 0);//获取送货地址网络ID
            totalMoney = intent.getDoubleExtra("debtMoney", 0);//获取客户要缴纳的金额
            txtStatisticsMoney.setText("结算金额："+FormatUtils.exactNumber(totalMoney,"0.00")+"元");
            lstCustomerDebtInfo = intent.getParcelableArrayListExtra("listDebt");//获取订单数据的详细列表
        }
        initActivity();//初始化基本数据
    }


    /**
     * 初始化页面
     */
    public void initActivity(){
        new AsyncTask<Void,Void,Void>(){
            private CustomerTable ct = null;
            private CustomerTypeTable ctt = null;
            private DeliverGoodsTable dt = null;
            private ProgressDialog dialog = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(DebtStatisticsActivity.this,"","正在加载...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    ct = dbUtils.findFirst(Selector.from(CustomerTable.class).where("id","=",netCustomerId));
                    dt = dbUtils.findFirst(Selector.from(DeliverGoodsTable.class).where("id","=",netAddressId));
                    if(dt!=null) ctt = dbUtils.findFirst(Selector.from(CustomerTypeTable.class).where("id","=",dt.khlx));
                    List<BankTable> banklst = dbUtils.findAll(BankTable.class);
                    if(banklst!=null && banklst.size() > 0) {
                        bankNames = new String[banklst.size()];
                        bankIds = new int[banklst.size()];
                        for (int i = 0; i < banklst.size(); i++) {
                            BankTable item = banklst.get(i);
                            bankNames[i] = item.mc;
                            bankIds[i] = item.id;
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null) dialog.dismiss();
                if(ct!=null && dt!=null && ctt!=null){
                    txtIcon.setText(ctt.dttb);
                    txtCustomerName.setText(ct.mc);
                    txtCustomerAddress.setText("地址："+dt.shdz);
                    txtContactor.setText(ct.lxr+" "+ct.dh);
                    txtDelieverGoodsInfo.setText(dt.shr+" "+dt.shdh);
                    if(bankNames!=null) txtBank.setText(bankNames[0]);
                    else txtBank.setEnabled(false);
                    if(SystemData.currentLocation!=null && !TextUtils.isEmpty(dt.jwd.toString())){//计算距离信息
                        String[] latlngs = dt.jwd.split(",");
                        txtDistance.setText(FormatUtils.exactDistance(new LatLng(SystemData.currentLocation.getLatitude(),
                                SystemData.currentLocation.getLongitude()),new LatLng(Double.parseDouble(latlngs[0]),
                                Double.parseDouble(latlngs[1]))));
                    }
                }else{
                    Toast.makeText(DebtStatisticsActivity.this, "页面初始化失败!", Toast.LENGTH_SHORT).show();
                    DebtStatisticsActivity.this.finish();
                }
            }
        }.execute();
    }

    /**
     * 视图控件点击事件
     * @param view
     */
    @OnClick(value = {R.id.pdebtStatistics_txtPrint, R.id.pdebtStatistics_txtDebtStatistics,
            R.id.pdebtStatistics_txtBank,R.id.pdebtStatistics_txtPayWay})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.pdebtStatistics_txtPrint://打印
                break;
            case R.id.pdebtStatistics_txtDebtStatistics://收欠款结算
                debtAllOrders(this);//提交当前所有数据
                break;
            case R.id.pdebtStatistics_txtBank://银行选择
                if(bankNames!=null && bankIds!=null) {
                    new AlertDialog.Builder(DebtStatisticsActivity.this).setItems(bankNames, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            txtBank.setText(bankNames[which]);
                            selectorIndex = which;
                        }
                    }).show();
                }else{
                    Toast.makeText(DebtStatisticsActivity.this,"没有银行账户数据可选择!",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.pdebtStatistics_txtPayWay://支付方式
                final String[] itemTexts = {"现金","银行"};
                new AlertDialog.Builder(DebtStatisticsActivity.this).setItems(itemTexts, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        txtPayWay.setText(itemTexts[which]);
                        txtBank.setEnabled(!txtPayWay.getText().toString().equals("现金"));
                    }
                }).show();
                break;
        }
    }


    /***
     * 结算操作
     * @return
     */
    public void debtAllOrders(final Context context){
        new AsyncTask<Void,Void,Void>(){

            private ProgressDialog dialog = null;
            private String errorMessage = null;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在提交数据...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                SQLiteDatabase database = dbUtils.getDatabase();
                try{
                    database.beginTransaction();
                    if(lstCustomerDebtInfo!=null && lstCustomerDebtInfo.size()>0){
                        int length = lstCustomerDebtInfo.size();
                        for(int i = 0;i<length;i++){
                            CustomerDebtTable item = lstCustomerDebtInfo.get(i);
                            String wsjeVal = FormatUtils.exactNumber(item.wsje ,"0.00");
                            String bcskVal = FormatUtils.exactNumber(item.payableMoney,"0.00");
                            if(wsjeVal.equals(bcskVal)){//当本次支付等于应收金额时，删除该数据
                                dbUtils.delete(item);
                            }else{
                                item.wsje = item.wsje - item.payableMoney;
                                item.cdje = item.payableMoney;
                                dbUtils.update(item,"wsje","cdje");
                            }
                            double malingVal = 0;//抹零数据
                            if(i == length-1){//如果是最后一项，写入抹零数据
                                String txtVal = etMaling.getText().toString();
                                if(TextUtils.isEmpty(txtVal) || txtVal.equals("-"))
                                    txtVal = "0";
                                malingVal = Double.valueOf(txtVal);
                            }
                            saveOrderStatistics(dbUtils,item,malingVal);
                        }
                    }
                    database.setTransactionSuccessful();
                }catch (Exception e){
                    errorMessage = "提交数据失败!原因："+e.getMessage();
                    e.printStackTrace();
                }
                database.endTransaction();
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null &&dialog.isShowing())
                    dialog.dismiss();
                if(errorMessage!=null){//提交数据失败
                    Toast.makeText(context,errorMessage,Toast.LENGTH_SHORT).show();
                }else{
                    DebtStatisticsActivity.this.finish();
                    startActivity(new Intent(context, MainActivity.class));
                    overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                    Toast.makeText(context,"提交数据成功！",Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    /**
     * 填写订单结算信息
     * @param dbUtils
     */
    public void saveOrderStatistics(DbUtils dbUtils,CustomerDebtTable cdt,double malingMoney) throws Exception{
        SaleStatisticsTable sst = new SaleStatisticsTable();
        sst.jsrq = FormatUtils.standardDatetime(new Date(),"yyyy-MM-dd HH:mm:ss");
        sst.xsd_id = cdt.djh;//销售单号
        sst.djh = cdt.djh;//单据号
        sst.kh_id = netCustomerId;//客户ID
        sst.shdz_id = netAddressId;//收货地址ID
        sst.jslx = 1;//结算类型 = 1,历史账单
        sst.jsje = cdt.payableMoney;//结算金额
        if(txtPayWay.getText().toString().equals("现金")) {
            sst.xjje = cdt.payableMoney;//现金金额
            sst.yhje = 0;//银行金额
            sst.yhzh_id = 0;//银行账户ID
            sst.yhzh = "";//银行账户
        }else {
            sst.xjje = 0 ;//现金金额
            sst.yhje = cdt.payableMoney;//银行金额
            sst.yhzh_id = bankIds[selectorIndex];//银行账户ID
            sst.yhzh = txtBank.getText().toString();//银行账户
        }
        sst.qkje = 0;//欠款金额
        sst.zqts = 0;//欠款天数
        sst.mlje = malingMoney;//抹零金额
        sst.bz = "";//备注信息
        dbUtils.save(sst);
    }


    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pdebtStatistics_txtBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
